package com.icongyou.enterprise.talent_analysis.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.common.exception.BusinessException;
import com.icongyou.enterprise.talent_analysis.entity.PortraitCache;
import com.icongyou.enterprise.talent_analysis.entity.PortraitResponse;
import com.icongyou.enterprise.talent_analysis.entity.PortraitUpdateTask;
import com.icongyou.enterprise.talent_analysis.mapper.PortraitCacheMapper;
import com.icongyou.enterprise.talent_analysis.mapper.PortraitUpdateTaskMapper;
import com.icongyou.enterprise.talent_analysis.service.AIPortraitEvaluationService;
import com.icongyou.enterprise.talent_analysis.service.PortraitAsyncService;
import com.icongyou.enterprise.talent_analysis.service.PortraitService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class PortraitAsyncServiceImpl implements PortraitAsyncService {

    private final PortraitUpdateTaskMapper taskMapper;
    private final PortraitCacheMapper cacheMapper;
    private final PortraitService portraitService;
    private final AIPortraitEvaluationService aiPortraitService;
    private final ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void triggerStudentPortraitUpdate(String studentId, String triggerSource) {
        
        // 清除该学生的所有缓存
        cacheMapper.deleteByStudentId(studentId);
        
        // 创建默认模板的更新任务
        PortraitUpdateTask defaultTask = new PortraitUpdateTask();
        defaultTask.setId(UUID.randomUUID().toString());
        defaultTask.setStudentId(studentId);
        defaultTask.setTemplateId(null);  // null表示默认模板
        defaultTask.setTriggerType("DATA_CHANGE");
        defaultTask.setTriggerSource(triggerSource);
        defaultTask.setStatus("PENDING");
        defaultTask.setRetryCount(0);
        defaultTask.setCreatedAt(LocalDateTime.now());
        taskMapper.insert(defaultTask);
        
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void triggerTemplatePortraitUpdate(String templateId) {
        
        // 清除该模板的所有缓存
        cacheMapper.deleteByTemplateId(templateId);
        
        // TODO: 查询使用该模板的所有学生，为每个学生创建更新任务
        // 这里需要根据实际业务逻辑实现
    }

    @Override
    @Scheduled(fixedDelay = 10000)  // 每10秒执行一次
    @Async
    public void processUpdateTasks() {
        List<PortraitUpdateTask> tasks = taskMapper.selectPendingTasks(10);
        
        if (tasks.isEmpty()) {
            return;
        }
        
        
        for (PortraitUpdateTask task : tasks) {
            try {
                processTask(task);
            } catch (Exception e) {
            }
        }
    }

    @Override
    @Scheduled(cron = "0 0 2 * * ?")  // 每天凌晨2点执行
    public void cleanupOldTasks() {
        int deleted = taskMapper.deleteCompletedBefore(7);
    }

    @Transactional(rollbackFor = Exception.class)
    protected void processTask(PortraitUpdateTask task) {
        // 标记为处理中
        taskMapper.updateToProcessing(task.getId());
        
        try {
            // 生成画像
            PortraitResponse response;
            if (task.getTemplateId() == null) {
                // 默认模板
                response = portraitService.computeDefaultPortrait(task.getStudentId());
            } else {
                // 自定义模板
                response = aiPortraitService.computeCustomPortrait(task.getStudentId(), task.getTemplateId());
            }
            
            // 保存到缓存
            saveToCache(task.getStudentId(), task.getTemplateId(), response);
            
            // 标记为完成
            task.setStatus("COMPLETED");
            task.setCompletedAt(LocalDateTime.now());
            taskMapper.updateToCompleted(task);
            
            
        } catch (Exception e) {
            task.setStatus("FAILED");
            task.setErrorMessage(e.getMessage());
            task.setRetryCount(task.getRetryCount() + 1);
            taskMapper.updateToFailed(task);
        }
    }

    private void saveToCache(String studentId, String templateId, PortraitResponse response) {
        try {
            PortraitCache cache = new PortraitCache();
            cache.setId(UUID.randomUUID().toString());
            cache.setStudentId(studentId);
            cache.setTemplateId(templateId);
            cache.setLabelsJson(objectMapper.writeValueAsString(response.getLabels()));
            cache.setScoresJson(objectMapper.writeValueAsString(response.getScores()));
            cache.setDimensionsJson(objectMapper.writeValueAsString(response.getDimensions()));
            cache.setAiUsed(response.isAiUsed());
            cache.setGeneratedAt(LocalDateTime.now());
            cache.setUpdatedAt(LocalDateTime.now());
            cache.setVersion(0);
            
            cacheMapper.insert(cache);
            
        } catch (JsonProcessingException e) {
            throw new BusinessException("画像数据序列化失败");
        }
    }
    
    @Override
    @Async
    public void triggerBatchUpdate(String templateId, String triggerSource) {
        
        // 这里简化处理：为所有使用该模板的学生创建更新任务
        // 实际应该查询哪些学生使用了该模板
    }
    
    @Override
    public void clearCacheByTemplate(String templateId) {
        cacheMapper.deleteByTemplateId(templateId);
    }
}
